package manager

import android.os.Environment
import ext.log
import okhttp3.*
import org.json.JSONObject
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.util.concurrent.TimeUnit

object HttpRequestManager {
    private var WECHAT_REFUND_URL = "${AppManager.baseUrl}/jf/com/pm/returnrefundWechat.json" // 微信退款接口
        get() = "${AppManager.baseUrl}/jf/com/pm/returnrefundWechat.json"

    private var ALIPAY_REFUND_URL = "${AppManager.baseUrl}/jf/com/pm/returnrefundAlipay.json" // 支付宝退款接口
        get() = "${AppManager.baseUrl}/jf/com/pm/returnrefundAlipay.json"

    private var QUERY_REFUND_URL = "${AppManager.baseUrl}/jf/com/pm/searchRefundStatus.json" // 查询退款
        get() = "${AppManager.baseUrl}/jf/com/pm/searchRefundStatus.json"

    private var QUERY_ORDER_URL = "${AppManager.baseUrl}/jf/com/pm/getCargoLane.json" // 查询订单接口
        get() = "${AppManager.baseUrl}/jf/com/pm/getCargoLane.json"

    private var ADV_URL = "${AppManager.baseUrl}/adviertisement/giveAdviertiseToClient.json" // 获取广告
        get() = "${AppManager.baseUrl}/adviertisement/giveAdviertiseToClient.json"

    private var WARES_URL = "${AppManager.baseUrl}/goodssearch/goods-info/list.json" // 获取商品信息
        get() = "${AppManager.baseUrl}/goodssearch/goods-info/list.json"

    private var REPLENISH_URL = "${AppManager.baseUrl}/replenishment/detail-inter/data.json" // 获取补货清单接口
        get() = "${AppManager.baseUrl}/replenishment/detail-inter/data.json"

    private var REPLENISH_COMPLETE_URL = "${AppManager.baseUrl}/replenishment/client/replen-data/finish.json" // 补货完成接口
        get() = "${AppManager.baseUrl}/replenishment/client/replen-data/finish.json"

    private var REPORT_URL = "${AppManager.baseUrl}/replenishment/work-off/quantity.json" // 扣减库存
        get() = "${AppManager.baseUrl}/replenishment/work-off/quantity.json"

    private var HEAT_URL = "${AppManager.baseUrl}/worn/giveTemp.json" // 温度控制
        get() = "${AppManager.baseUrl}/worn/giveTemp.json"

    private var TEMP_URL = "${AppManager.baseUrl}/worn/give.json" // 温度报警
        get() = "${AppManager.baseUrl}/worn/give.json"

    private var CHECK_URL = "${AppManager.baseUrl}/checkMain/main-info/check.json" // 校验用户
        get() = "${AppManager.baseUrl}/checkMain/main-info/check.json"

    private var SELL_STATUS_URL = "${AppManager.baseUrl}/sbzt/giveStatus.json" // 获取停售or在售状态
        get() = "${AppManager.baseUrl}/sbzt/giveStatus.json"

    private var GOODS_TYPE_INFO_URL = "${AppManager.baseUrl}/cargoconfig/web/cargo.json" // 获取货道信息
        get() = "${AppManager.baseUrl}/cargoconfig/web/cargo.json"

    private var STATUS_CHANGED_URL = "${AppManager.baseUrl}/status/receiveAquarius.json" // 状态
        get() = "${AppManager.baseUrl}/status/receiveAquarius.json" // 状态

    private var STATUS_3_URL = "${AppManager.baseUrl}/status/receiveAquariusTemperature.json"
        get() = "${AppManager.baseUrl}/status/receiveAquariusTemperature.json"

    private var QUERY_PAY_URL = "${AppManager.baseUrl}/jf/com/pm/order/ispay.json"
        get() = "${AppManager.baseUrl}/jf/com/pm/order/ispay.json"

    private val WebPushUrl = "http://106.12.198.37:54300/push" // WebPush

    private val mHttpClient =
        OkHttpClient.Builder().connectTimeout(10, TimeUnit.SECONDS).writeTimeout(10, TimeUnit.SECONDS)
            .readTimeout(10, TimeUnit.SECONDS).build()

    private val mMediaType = MediaType.parse("application/json; charset=utf-8")

    private fun post(url: String, content: String): String {
        val body = RequestBody.create(mMediaType, content)
        val request = Request.Builder().url(url).post(body).build()
        val call = mHttpClient.newCall(request)
        val response = call.execute()
        return response.body()?.string() ?: throw IOException("network error")
    }

    fun refreshControlHeatData(): String {
        val json = JSONObject()
        json.put("macAddr", AppManager.MacAddress)
        val content = json.toString()
        return post(HEAT_URL, content)
    }

    /**
     * 报警温度
     */
    fun refreshTempValue(): String {
        val json = JSONObject()
        json.put("macAddr", AppManager.MacAddress)
        val content = json.toString()
        return post(TEMP_URL, content)
    }

    /**
     * 刷新广告信息
     */
    fun refreshAdvWithServer(): String {
        val json = JSONObject()
        json.put("macAddr", AppManager.MacAddress)
        val content = json.toString()
        log(content, "获取广告-请求")
        return post(ADV_URL, content)
    }

    fun checkIdAndPassword(id: String, password: String): Boolean {
        val jsonObject = JSONObject()
        jsonObject.put("emplCode", id)
        jsonObject.put("password", password)
        jsonObject.put("macAddr", AppManager.MacAddress)

        val result = post(CHECK_URL, jsonObject.toString())
        log("登陆返回:$result")
        val json = JSONObject(result)
        val ret = json.optBoolean("success")
        return ret
    }

    fun downLoadFile(name: String, url: String): File {
        log("开始下载:$name")
        val request = Request.Builder().get().url(url).build()
        val call = mHttpClient.newCall(request)
        val response = call.execute()
        val bytes = response.body()!!.bytes()
        log("下载的数据大小:${bytes.size}")
        val file = File(Environment.getExternalStorageDirectory(), name)
        if (file.exists()) {
            file.delete()
        }
        val ret = file.createNewFile()
        log("创建文件:$ret")
        val out = FileOutputStream(file, false)
        out.write(bytes)
        out.flush()
        out.close()
        return file
    }

    fun downLoadOTA(url: String): ByteArray {
        val request = Request.Builder().get().url(url).build()
        val call = mHttpClient.newCall(request)
        val response = call.execute()
        if (response.code() != 200) {
            log("下载文件错误:${response.code()}")
            return byteArrayOf(0)
        }
        return response.body()!!.bytes()
    }

    /**
     * 刷新机器在售停售消息
     */
    fun refreshSellWithServer(): String {
        val json = JSONObject()
        json.put("macAddr", AppManager.MacAddress)
        return post(SELL_STATUS_URL, json.toString())
    }

    /**
     * 使用支付宝进行退款
     */
    fun refundWithAlipay(order: String, remark: String, goodsType: String) {
        val body = MultipartBody.Builder().addFormDataPart("out_trade_no", order)
            .addFormDataPart("macAddr", AppManager.MacAddress).addFormDataPart("refund_remark", remark)
            .addFormDataPart("cargoData", goodsType).build()
        val request = Request.Builder().url(ALIPAY_REFUND_URL).post(body).build()
        val ret = mHttpClient.newCall(request).execute().body()?.string() ?: ""
        log("支付宝退款返回:$ret")
    }

    /**
     * 使用微信进行退款
     */
    fun refundWithWechat(order: String, remark: String, goodsType: String) {
        val body = MultipartBody.Builder().addFormDataPart("out_trade_no", order)
            .addFormDataPart("macAddr", AppManager.MacAddress).addFormDataPart("refund_remark", remark)
            .addFormDataPart("cargoData", goodsType).build()
        val request = Request.Builder().url(WECHAT_REFUND_URL).post(body).build()
        val ret = mHttpClient.newCall(request).execute().body()?.string() ?: ""
        log("微信退款返回:$ret")
    }

    /**
     * 查询退款
     */
    fun queryRefund(order: String): String {
        val body = FormBody.Builder().add("out_trade_no", order).build()
        val request = Request.Builder().post(body).url(QUERY_REFUND_URL).build()
        return mHttpClient.newCall(request).execute().body()?.string() ?: "error"
    }

    /**
     * 查询订单
     */
    fun queryOrder(order: String): String {
        val body = FormBody.Builder().add("out_trade_no", order).build()
        val request = Request.Builder().post(body).url(QUERY_ORDER_URL).build()
        return mHttpClient.newCall(request).execute().body()?.string() ?: "error"
    }

    /**
     * 刷新库存
     */
    fun refreshInventory(): String {
        val json = JSONObject()
        json.put("macAddr", AppManager.MacAddress)
        val content = json.toString()
        return post(WARES_URL, content)
    }

    /**
     * 获取补货清单
     */
    fun refreshReplenishList(): String {
        val json = JSONObject()
        json.put("macAddr", AppManager.MacAddress)
        val content = json.toString()
        return post(REPLENISH_URL, content)
    }

    /**
     * 扣减库存
     */
    fun reportRepertory(goodsType: String, order: String): String {
        val jsonObject = JSONObject()
        jsonObject.put("macAddr", AppManager.MacAddress)
        jsonObject.put("cargoData", goodsType)
        jsonObject.put("out_trade_no", order)
        log(jsonObject.toString())
        val res = post(REPORT_URL, jsonObject.toString())
        log("扣减库存:$res")
        return res
    }

    /**
     * 补货完成
     */
    fun replenishComplete(content: String) = post(REPLENISH_COMPLETE_URL, content)

    /**
     * 状态发生变化的时候上传状态信息
     */
    fun uploadStatusWithChanged(content: String): String {
        return post(STATUS_CHANGED_URL, content)
    }

    /**
     * 每隔3分钟上传一次状态
     */
    fun uploadStatusWith3(content: String): String {
        return post(STATUS_3_URL, content)
    }

    fun queryPay(): Boolean {
        val root = JSONObject()
        root.put("out_trade_no", PayManager.CurrentOrder)
        val reqBody = root.toString()
        log("查询支付信息:$reqBody")
        val respBody = post(QUERY_PAY_URL, reqBody)
        log("支付信息返回:$respBody")
        val resp = JSONObject(respBody)
        return resp.getBoolean("success")
    }

    /**
     * 刷新货道信息
     */
    fun refreshGoodsTypeInfo(): String {
        val json = JSONObject()
        json.put("macAddr", AppManager.MacAddress)
        val content = json.toString()
        return post(GOODS_TYPE_INFO_URL, content)
    }

    /**
     * 向Web发送信息
     */
    fun postWebMessage(message: String): String {
        val body = FormBody.Builder()
            .add("Content", message)
            .add("Receive", PayManager.CurrentOrder)
            .build()
        val request = Request.Builder()
            .url(WebPushUrl)
            .post(body)
            .build()
        return mHttpClient.newCall(request).execute().body()?.string() ?: throw IOException("网络错误")
    }

}